<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <el-card class="toolbar-card">
      <div class="toolbar-right">
        <el-input v-model="searchKeyword" placeholder="搜索设备名称" clearable style="width: 400px;"
          @keyup.enter="loadDevices">
        </el-input>

        <el-select v-model="filterStatus" placeholder="状态筛选" clearable @change="loadDevices"
          style="width: 300px;margin: 0 20px;">
          <el-option label="全部状态" value="" />
          <el-option label="在线" value="1" />
          <el-option label="离线" value="0" />
        </el-select>
        <el-button type="primary" @click="loadDevices" icon="search">
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon>
            <Refresh />
          </el-icon>
          重置
        </el-button>
      </div>
    </el-card>

    <el-card class="mt-2">
      <el-button type="primary" icon="Refresh" @click="handleSync" :loading="syncing">
        同步设备
      </el-button>
      <!-- <el-button type="success" icon="Download" @click="handleExport" :disabled="!selectedDevice">
        导出日志
      </el-button>
      <el-button type="warning" icon="Connection" @click="showBindDialog" :disabled="!selectedDevice">
        关联站点
      </el-button> -->
      <div class="device-table-container mt-2">
        <el-table :data="deviceList" v-loading="loading" highlight-current-row @row-click="handleRowClick"
          style="width: 100%">
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column label="设备信息 " align="center">
            <template #default="{ row }">
              <div class="device-info">
                <div class="device-name">
                  <el-icon :color="getStatusColor(row.deviceStatus)" class="status-icon">
                    <CircleFilled />
                  </el-icon>
                  {{ row.deviceName }}
                </div>
                <div class="device-meta">
                  <span class="ip-address">{{ row.ipAddress }}:{{ row.port }}</span>
                  <span class="device-model">{{ row.deviceModel }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="站点名称" align="center" prop="siteName"></el-table-column>
          <el-table-column label="状态" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.deviceStatus)" size="small">
                {{ getStatusText(row.deviceStatus) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="最后同步" align="center">
            <template #default="{ row }">
              {{ formatTime(row.lastSyncTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="400" fixed="right" align="center">
            <template #default="{ row }">
              <el-button-group size="small" style="margin-right: 10px;">
                <el-button type="primary" @click="handleControl(row, 3)" :disabled="row.deviceStatus !== 1">
                  开门
                </el-button>
                <el-button type="warning" @click="handleControl(row, 4)" :disabled="row.deviceStatus !== 1">
                  关门
                </el-button>
              </el-button-group>
              <el-button type="info" size="small" @click="showDetailDialog(row)">
                详情
              </el-button>
              <el-button type="success" size="small" @click="showLogDialog(row)">
                日志
              </el-button>
              <el-button type="success" size="small" @click="showBindDialog(row)" v-if="!row.siteName">
                关联站点
              </el-button>
              <el-button type="danger" size="small" @click="handleUnbindSite(row)" v-if="row.siteName">
                解除关联
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-row class="pagination-row">
        <el-col :span="24">
          <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
              :total="deviceTotal" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 设备详情弹窗 -->
    <el-dialog :title="`设备详情 - ${selectedDevice?.deviceName || ''}`" v-model="detailDialogVisible">
      <el-descriptions :column="1" border size="small">
        <el-descriptions-item label="设备ID">{{ selectedDevice.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ selectedDevice.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{ selectedDevice.deviceModel }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedDevice.ipAddress }}:{{
          selectedDevice.port }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="getStatusTagType(selectedDevice.deviceStatus)">
            {{ getStatusText(selectedDevice.deviceStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="关联站点">
          {{ selectedDevice.siteName || '未关联' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(selectedDevice.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(selectedDevice.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="最后同步">{{ formatTime(selectedDevice.lastSyncTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ selectedDevice.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="showLogDialog(selectedDevice)">查看日志</el-button>
      </template>
    </el-dialog>

    <!-- 设备日志弹窗 -->
    <el-dialog :title="`设备日志 - ${selectedDevice?.deviceName || ''}`" v-model="logDialogVisible"
      :close-on-click-modal="false">
      <div v-if="selectedDevice" class="log-dialog-content">
        <el-row class="log-filter">
          <el-col :span="24">
            <el-form :inline="true">
              <el-form-item label="时间范围">
                <el-date-picker v-model="logDateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="loadDeviceLogs" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="loadDeviceLogs">查询</el-button>
                <el-button icon="Refresh" @click="resetLogFilter">重置</el-button>
                <el-button type="success" icon="Download" @click="handleExport">导出日志</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <div class="log-table-container">
              <el-table :data="logList" v-loading="logLoading" size="small" style="width: 100%">
                <el-table-column prop="operateTime" label="操作时间" align="center">
                  <template #default="{ row }">
                    {{ formatTime(row.operateTime) }}
                  </template>
                </el-table-column>

                <el-table-column prop="operateType" label="操作类型" align="center">
                  <template #default="{ row }">
                    <el-tag size="small">
                      {{ getLogName(row.operateType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="operatorName" label="操作人" align="center" />
                <el-table-column prop="operateResult" label="操作结果" align="center">
                  <template #default="{ row }">
                    <el-tag :type="row.operateResult == 1 ? 'success' : 'danger'" size="small">
                      {{ row.operateResult == 1 ? '成功' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>

        <el-row class="log-pagination">
          <el-col :span="24">
            <div class="pagination-container">
              <el-pagination v-model:current-page="logPagination.currentPage" v-model:page-size="logPagination.pageSize"
                :total="logTotal" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleLogSizeChange" @current-change="handleLogCurrentChange" />
            </div>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <el-button @click="logDialogVisible = false">关闭</el-button>
        <!-- <el-button type="primary" @click="showDetailDialog(selectedDevice)">查看详情</el-button> -->
      </template>
    </el-dialog>

    <!-- 关联站点弹窗 -->
    <el-dialog title="关联站点" v-model="bindDialogVisible" width="400px" center>
      <el-form :model="bindForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备名称">
              <el-input :value="selectedDevice?.deviceName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择站点" required>
              <el-select v-model="bindForm.siteId" placeholder="请选择站点" style="width: 100%" filterable>
                <el-option v-for="site in siteList" :key="site.siteId" :label="site.siteName" :value="site.siteId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-button @click="bindDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleBind" :loading="binding">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// API导入
import {
  syncDevices,
  getDeviceList,
  getDeviceLogs,
  exportDeviceLogs,
  controlDevice,
  getSiteList,
  bindDeviceSite,
  unbindDeviceSite
} from '@/api/park/entrance'

// 响应式数据
const loading = ref(false)
const logLoading = ref(false)
const syncing = ref(false)
const binding = ref(false)
const deviceList = ref([])
const logList = ref([])
const siteList = ref([])
const selectedDevice = ref(null)
const searchKeyword = ref('')
const filterStatus = ref('')
const bindDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const logDialogVisible = ref(false)
const logDateRange = ref([])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

const logPagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 总条数
const deviceTotal = ref(0)
const logTotal = ref(0)

// 表单数据
const bindForm = reactive({
  siteId: ''
})

// 计算属性
const onlineCount = computed(() => {
  return deviceList.value.filter(device => device.deviceStatus === 1).length
})

const offlineCount = computed(() => {
  return deviceList.value.filter(device => device.deviceStatus === 0).length
})

// 生命周期
onMounted(() => {
  loadDevices()
  loadSites()
})

const handleReset = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  pagination.currentPage = 1
  loadDevices()
}

// 方法定义
const loadDevices = async () => {
  try {
    loading.value = true
    const params = {
      deviceName: searchKeyword.value,
      deviceStatus: filterStatus.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getDeviceList(params)
    if (res.code === 200) {
      deviceList.value = res.rows
      deviceTotal.value = res.total // 设置总条数

      // 如果没有选中设备，默认选中第一个
      if (!selectedDevice.value && res.rows.length > 0) {
        selectedDevice.value = res.rows[0]
      }
    } else {
      ElMessage.error(res.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  } finally {
    loading.value = false
  }
}

const loadSites = async () => {
  try {
    const res = await getSiteList()
    if (res.code === 200) {
      siteList.value = res.data
    }
  } catch (error) {
    console.error('加载站点失败:', error)
  }
}

// 解除站点关联
const handleUnbindSite = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除设备 "${row.deviceName}" 的站点关联吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await unbindDeviceSite(row.deviceId);
    ElMessage.success('站点关联已解除')
    handleReset();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除关联失败:', error)
      ElMessage.error('解除关联失败')
    }
  }
}

const loadDeviceLogs = async () => {
  if (!selectedDevice.value) return

  try {
    logLoading.value = true
    const params = {
      deviceId: selectedDevice.value.deviceId,
      pageNum: logPagination.currentPage,
      pageSize: logPagination.pageSize
    }

    if (logDateRange.value && logDateRange.value.length == 2) {
      params.startTime = logDateRange.value[0]
      params.endTime = logDateRange.value[1]
    }

    const res = await getDeviceLogs(params)
    if (res.code === 200) {
      logList.value = res.rows
      logTotal.value = res.total // 设置日志总条数
    } else {
      ElMessage.error(res.msg || '加载日志失败')
    }
  } catch (error) {
    ElMessage.error('加载日志失败')
  } finally {
    logLoading.value = false
  }
}

const handleSync = async () => {
  try {
    syncing.value = true
    const res = await syncDevices()
    if (res.code === 200) {
      ElMessage.success('同步成功')
      loadDevices()
    } else {
      ElMessage.error(res.msg || '同步失败')
    }
  } catch (error) {
    ElMessage.error('同步失败')
  } finally {
    syncing.value = false
  }
}

const handleExport = async () => {
  // 使用proxy.download进行导出
  // proxy.download('/system/dispatchAmountWater/export', { deviceId: }, fileName)
  // ElMessage.success('导出任务已开始')
}

const handleControl = async (device, command) => {
  try {
    const action = command === 3 ? '开门' : '关门'
    await ElMessageBox.confirm(`确定要${action}设备【${device.deviceName}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await controlDevice({
      deviceId: device.deviceId,
      command: command
    })

    if (res.code === 200) {
      ElMessage.success(`${action}指令发送成功`)
      // 如果日志弹窗已打开，刷新日志
      if (logDialogVisible.value) {
        loadDeviceLogs()
      }
    } else {
      ElMessage.error(res.msg || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleRowClick = (row) => {
  selectedDevice.value = row
}

const showDetailDialog = (device) => {
  selectedDevice.value = device
  detailDialogVisible.value = true
}

const showLogDialog = (device) => {
  selectedDevice.value = device
  logDialogVisible.value = true
  // 重置分页和筛选条件
  logPagination.currentPage = 1
  logDateRange.value = []
  loadDeviceLogs()
}

const showBindDialog = (row) => {
  bindForm.siteId = row.siteId || '';
  bindDialogVisible.value = true
}

const handleBind = async () => {
  if (!bindForm.siteId) {
    ElMessage.warning('请选择站点')
    return
  }

  try {
    binding.value = true
    const res = await bindDeviceSite({
      deviceId: selectedDevice.value.deviceId,
      siteId: bindForm.siteId
    })

    if (res.code === 200) {
      ElMessage.success('关联成功')
      bindDialogVisible.value = false
      loadDevices()
      // 如果详情弹窗已打开，刷新数据
      if (detailDialogVisible.value) {
        // 重新加载设备数据以获取更新后的站点信息
        const updatedDevice = deviceList.value.find(d => d.deviceId === selectedDevice.value.deviceId)
        if (updatedDevice) {
          selectedDevice.value = { ...updatedDevice }
        }
      }
    } else {
      ElMessage.error(res.msg || '关联失败')
    }
  } catch (error) {
    ElMessage.error('关联失败')
  } finally {
    binding.value = false
  }
}

const resetLogFilter = () => {
  logDateRange.value = []
  logPagination.currentPage = 1
  loadDeviceLogs()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadDevices()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadDevices()
}

const handleLogSizeChange = (size) => {
  logPagination.pageSize = size
  logPagination.currentPage = 1
  loadDeviceLogs()
}

const handleLogCurrentChange = (page) => {
  logPagination.currentPage = page
  loadDeviceLogs()
}

// 工具函数
const getStatusColor = (status) => {
  const colors = {
    0: '#F56C6C', // 离线-红色
    1: '#67C23A', // 在线-绿色
    2: '#E6A23C'  // 同步中-黄色
  }
  return colors[status] || '#909399'
}

const getStatusTagType = (status) => {
  const types = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    0: '离线',
    1: '在线',
    2: '同步中'
  }
  return texts[status] || '未知'
}

const getLogName = (type) => {
  const types = {
    '1': '远程开门',
    '2': '远程关门',
    '3': '同步设备',
    '4': '关联站点',
  }
  return types[type]
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.toolbar-card {
  margin-bottom: 16px;
}

.toolbar-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.mt-2 {
  margin-top: 16px;
}

.device-table-container {
  min-height: 400px;
}

.device-info {
  text-align: left;
}

.device-name {
  display: flex;
  align-items: center;
  font-weight: 500;
  margin-bottom: 4px;
}

.status-icon {
  margin-right: 8px;
}

.device-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.ip-address,
.device-model {
  flex: 1;
}

.pagination-row {
  margin-top: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.log-dialog-content {
  min-height: 400px;
}

.log-filter {
  margin-bottom: 16px;
}

.log-table-container {
  min-height: 300px;
}

.log-pagination {
  margin-top: 16px;
}
</style>